import React, { memo, Component } from 'react'
import { getLostThingList, createLostThing, setThingQuestion } from '@/api/user'
import {
  Spin,
  Upload,
  Modal,
  Form,
  Input,
  Button,
  message,
  Tooltip,
  Popconfirm,
  Select
} from 'antd'
import './index.css'
import { baseUrl } from '../../assets/baseUrl'
import { PlusOutlined } from '@ant-design/icons'
import { getDateDiff } from '../../utils/tool'
import { StudentInfo } from '../../utils/model'
import { postGoods, getSchoolList,getGoodsList } from '@/api/index';
import $ from 'jquery'
const BaseUrl = baseUrl()
const { TextArea } = Input
const { Option } = Select;
// import { NotificationOutlined } from '@ant-design/icons';
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
class searchPeople extends Component {
  static contextType = StudentInfo
  constructor(props) {
    super(props)
    this.state = {
      type: props.type, //1--找失物   2---找失主
      loading: false,
      releaseVisible: false,
      lostThingList: [], //遗失物品列表
      fileList: [], //图片列表
      content: '', //内容
      findTime: '', //发现时间
      findPlace: '', //发现地点
      tag: '', //物品类型
      numberId: null,
      campus:null,
      startTime: 'null', //获取列表的开始时间
      pageCount: 20, //每次获取的条数
      setQuestionVisible: false, //设置问题弹框是否可见
      questions: [''], //认领问题
      studentId: null,
      schoolSect:[],
    }
  }
  componentDidMount() {
    this.setState({
      studentId: this.context?.studentInfo?.studentId
    },()=>{
      this.handleScroll()
      this.getList()
      this.getSchoolDate()
    })
  }
  //获取校区列表
   getSchoolDate = async () => {
    const res = await getSchoolList()
    this.setState({schoolSect:res.data?.campus})
    // setschoolSect()
  }
  getList = () => {
    let { startTime, pageCount, lostThingList, type } = this.state
    getLostThingList({
      startTime: startTime,
      pageCount: pageCount,
      type: type
    }).then((res) => {
      let results = res.data?.results
      this.setState({
        lostThingList: [...lostThingList, ...results],
        startTime: results[results.length - 1]?.createTime || startTime
      })
    })
  }
  //监听滚条滚动到底部
  handleScroll = () => {
    var nScrollHight = 0 //滚动距离总长(注意不是滚动条的长度)
    var nScrollTop = 0 //滚动到的当前位置
    var nDivHight = $('#view').height()
    $('#view').on('scroll', () => {
      nScrollHight = $('#view')[0].scrollHeight
      nScrollTop = $('#view')[0].scrollTop
      let paddingBottom = parseInt($('#view').css('padding-bottom')),
        paddingTop = parseInt($('#view').css('padding-top'))
      if (nScrollTop + paddingBottom + paddingTop + nDivHight >= nScrollHight) {
        this.getList() //滚动到底部了，触发此函数
      }
    })
  }
  handleCancel = () => this.setState({ previewVisible: false })
  handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    })
  }

  handleChange = ({ fileList }) => this.setState({ fileList })

  getUrls() {
    //拼接失物图片url
    let { fileList } = this.state
    let url = ''
    fileList.map((item) => {
      url = url + item.response + '&'
    })
    return url
  }

  //点击发布触发
  async handleSubmit(openQuestionModal) {
    let { content, findTime, findPlace, tag, lostThingList, type,campus } = this.state
    if (content == '') {
      message.warning('描述内容为必填项')
      return
    }
    let thingImg = await this.getUrls()
    if (thingImg == '') {
      message.warning('请上传图片再发布！')
      return
    }
    let createTime = Date.parse(new Date())
    let data = {
      createTime,
      content,
      thingImg,
      findTime,
      findPlace,
      forPeople: type == 1 ? 1 : 0,
      forThing: type == 1 ? 0 : 1,
      tag,
      campus
    }
    createLostThing(data).then((res) => {
      //信息清空
      data.numberId = res.data?.numberId
      this.setState({
        lostThingList: [data, ...lostThingList],
        content: '',
        findTime: '',
        findPlace: '',
        tag: '',
        campus:null,
        numberId: res.data?.numberId,
        releaseVisible: false //关闭弹窗
      })
      message.success('发布成功！')
      if (openQuestionModal == 1) {
        this.setState({
          setQuestionVisible: true
        })
      }
    })
  }

  //去详情页
  goToDetail(id) {
    this.props.goDetail(`/home/schoolIndex/thingLostDetail?numberId=${id}`)
  }

  confirm(e) {
    this.handleSubmit(1)
  }

  cancel = (e) => {
    this.handleSubmit()
  }

  //设置认领问题
  handleQuestion = () => {
    let { questions, numberId } = this.state
    let allRight = true
    questions.map((item, index) => {
      if (item == '') {
        message.warning(`请设置第${index + 1}个问题`)
        allRight = false
        return
      }
      if (item.length > 30) {
        allRight = false
        message.warning(`第${index + 1}个问题过长！限长30字~`)
        return
      }
    })
    if (allRight) {
      let data = {
        questions: questions.join('QUE'),
        numberId: numberId
      }
      setThingQuestion(data).then((res) => {
        message.success('认领问题设置成功！')
        this.setState({
          setQuestionVisible: false
        })
      })
    }
  }

  //点击我要发布
  openReleaseModal = () => {
    if (!this.context?.studentId?.schoolId) {
      Modal.warning({
        title: '温馨提示',
        content:
          '你还未加入学校，无法发布失物招领，请前往个人中心选择学校与班级~'
      })
      return
    } else {
      this.setState({
        releaseVisible: true
      })
    }
  }
  render() {
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传图片</div>
      </div>
    )
    const {
      lostThingList,
      fileList,
      previewVisible,
      previewImage,
      content,
      findTime,
      findPlace,
      releaseVisible,
      tag,
      type,
      setQuestionVisible,
      studentId
    } = this.state
    const formItemLayout = {
      labelCol: {
        span: 10
      },
      wrapperCol: { span: 14 }
    }
    return (
      <Spin spinning={this.state.loading} size="large">
        <div style={{}}>
          <div style={{ height: 40 }}>
            <Button
              className="thing_fabuButton"
              onClick={this.openReleaseModal.bind(this)}
            >
              我要发布
            </Button>
          </div>
          <div>
            <div
              className="flex"
              id="view"
              style={{
                margin: '0 auto',
                height: '80vh',
                overflowY: 'auto',
                padding: '0 7vw',
                flexWrap: 'wrap',
                justifyContent: 'flex-start'
              }}
            >
              {/* <div className='flex' style={{flexWrap:'wrap'}}> */}
              {lostThingList.map((item, index) => {
                return (
                  <div
                    className="thingBox"
                    onClick={this.goToDetail.bind(this, item.numberId)}
                  >
                    <div
                      className="lostImg"
                      style={{
                        background: `#fff url(${BaseUrl}${
                          item.thingImg.split('&')[0]
                        }) no-repeat center center`,
                        backgroundSize: 'auto 100%'
                      }}
                    />
                    <div className="messAll-Box">
                      <div
                        style={{ color: 'red', fontWeight: 600, fontSize: 14 }}
                      >
                        {item.tag}
                        <div
                          style={{
                            textAlign: 'right',
                            color: '#fce72a',
                            fontSize: 6
                          }}
                        >
                          {getDateDiff(item.createTime)}
                        </div>
                      </div>
                      <div className="contentDet">{item.content}</div>
                    </div>
                  </div>
                )
              })}
              {/* </div> */}
            </div>
          </div>
          <div>
            <Modal
              visible={releaseVisible}
              title={type === 1 ? '发布失物招领' : '发布寻物启事'}
              width="60vw"
              footer={null}
              onCancel={() => this.setState({ releaseVisible: false })}
            >
              <Form {...formItemLayout} layout={'horizontal'}>
                <Form.Item label="上传图片">
                  <Upload
                    action="https://www.donglongdong.xyz/fileUpload"
                    data={{
                      useMethod: '上传失物招领/寻物启事图片',
                      studentId: studentId
                    }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    style={{ height: '15vh', display: 'flex' }}
                  >
                    {fileList.length >= 3 ? null : uploadButton}
                  </Upload>
                </Form.Item>
                <Form.Item
                name="campus"
                label="校区"
                rules={[
                  {
                    required: true,
                    message: '请选择校区',
                  },
                ]}
                style={{
                 
                  borderRadius: '12px'
                }}
              >
                <Select  style={{
                      background: 'rgba(255, 255, 255,.6)',
                      width: '25vw',
                      borderRadius: '12px'
                    }}  placeholder="请选择校区" onChange={(e) =>{console.log('phh'); this.setState({ campus: e })}}>
                  {this.state.schoolSect?.map((item, index) => {
                    return <Option value={item.campusName}>{item.campusName}</Option>
                  })

                  }
                </Select>
              </Form.Item>
                <Form.Item label="物品类型" style={{ marginTop: 8 }}>
                  
                  <Input
                    placeholder="请输入物品类型"
                    style={{
                      background: 'rgba(255, 255, 255,.6)',
                      width: '25vw',
                      borderRadius: '12px'
                    }}
                    onChange={(e) => this.setState({ tag: e.target.value })}
                    value={tag}
                  />
                </Form.Item>
                <Form.Item label="描述内容">
                  <TextArea
                    placeholder="请输入内容"
                    style={{
                      background: 'rgba(255, 255, 255,.6)',
                      maxHeight: '15vh',
                      minHeight: '15vh',
                      width: '30vw',
                      height: '15vh',
                      borderRadius: '12px'
                    }}
                    onChange={(e) => this.setState({ content: e.target.value })}
                    value={content}
                  />
                </Form.Item>
                <Form.Item
                  label={type === 1 ? '时间' : '遗失时间'}
                  style={{ marginTop: 8 }}
                >
                  <Input
                    placeholder="请输入时间"
                    style={{
                      background: 'rgba(255, 255, 255,.6)',
                      width: '25vw',
                      borderRadius: '12px'
                    }}
                    onChange={(e) =>
                      this.setState({ findTime: e.target.value })
                    }
                    value={findTime}
                  />
                </Form.Item>
                <Form.Item
                  label={type === 1 ? '地点' : '遗失地点'}
                  style={{ marginTop: 8 }}
                >
                  <Input
                    placeholder="请输入地点"
                    style={{
                      background: 'rgba(255, 255, 255,.6)',
                      width: '25vw',
                      borderRadius: '12px'
                    }}
                    onChange={(e) =>
                      this.setState({ findPlace: e.target.value })
                    }
                    value={findPlace}
                  />
                </Form.Item>
                <Form.Item>
                  {type == 1 && (
                    <Popconfirm
                      title="是否为本条失物招领设置认领问题？"
                      onConfirm={this.confirm.bind(this)}
                      onCancel={this.cancel.bind(this)}
                      okText="发布后设置问题"
                      cancelText="发布但不设置问题"
                    >
                      <Tooltip
                        placement="bottom"
                        title="我承诺发布内容均属实，若发布虚假内容自愿承担封号风险"
                      >
                        <Button
                          style={{
                            marginLeft: '28vw',
                            backgroundColor: 'rgb(144, 198, 248)',
                            borderRadius: 8
                          }}
                        >
                          发布
                        </Button>
                      </Tooltip>
                    </Popconfirm>
                  )}
                  {type == 2 && (
                    <Tooltip
                      placement="bottom"
                      title="我承诺发布内容均属实，若发布虚假内容自愿承担封号风险"
                    >
                      <Button
                        style={{
                          marginLeft: '28vw',
                          backgroundColor: 'rgb(144, 198, 248)',
                          borderRadius: 8
                        }}
                        onClick={this.handleSubmit.bind(this)}
                      >
                        发布
                      </Button>
                    </Tooltip>
                  )}
                </Form.Item>
              </Form>
            </Modal>
            <Modal
              visible={previewVisible}
              title="预览图片"
              footer={null}
              onCancel={this.handleCancel}
            >
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
            <Modal
              visible={setQuestionVisible}
              title="设置认领问题"
              onCancel={() =>
                this.setState({ setQuestionVisible: false, questions: [''] })
              }
              okText={'提交'}
              cancelText={'不设置问题'}
              onOk={this.handleQuestion}
            >
              <ul>
                {this.state.questions?.map((item, index) => {
                  return (
                    <li style={{ margin: '10px 10px' }}>
                      <div>
                        {`认领问题${index + 1}：`}
                        <Input
                          placeholder="请设置认领问题"
                          style={{ width: '60%' }}
                          value={this.state.questions[index]}
                          onChange={(e) => {
                            let { questions } = this.state
                            questions[index] = e.target.value
                            this.setState({
                              questions
                            })
                          }}
                        />
                      </div>
                    </li>
                  )
                })}
                <div>
                  <Button
                    type="primary"
                    block
                    style={{ marginTop: 25, borderRadius: 12 }}
                    onClick={() => {
                      let { questions } = this.state
                      questions.push('')
                      this.setState({
                        questions
                      })
                    }}
                  >
                    增加认领问题
                  </Button>
                </div>
              </ul>
            </Modal>
          </div>
        </div>
      </Spin>
    )
  }
}
export default memo(searchPeople)
